/**
 * 
 */
package org.framework2.test.webserver.http.script;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * <p>
 * 脚本文件适配器，
 * </p>
 * @see 
 * @author ahli
 * @version WebServerTestMockV1, 2010-8-19
 * @since WebServerTestMockV1
 */
public class ScriptFileAdapter {

	/**
	 * 脚本文件处理器映射
	 */
	Map<String, ScriptFileHandler> scriptFileHandlerMap = new HashMap<String, ScriptFileHandler>();
	
	/**
	 * 文件映射
	 */
	Map<String, String> filesMap = new HashMap<String, String>();

	/**
	 * 日志对象
	 */
	private static final Log log = LogFactory.getLog(ScriptFileAdapter.class);
	
	/**
	 * 是否重载标识符，如果为true，则表示每次都将从磁盘读取文件内容
	 */
	private boolean reload = false;
	
	/**
	 * 初始化方法
	 */
	public void init(){
		for(Map.Entry<String, String> entry : filesMap.entrySet()){
			String uri = entry.getKey();
			String filePath = entry.getValue();
			ScriptFileHandler sfh = new ScriptFileHandler(filePath);
			try {
				sfh.readFile();
				scriptFileHandlerMap.put(uri, sfh);
			} catch (IOException e) {
				throw new RuntimeException("URI:" + uri + ", exception:" + e.toString());
			}
		}
	}
	
	/**
	 * 获取脚本内容
	 * @param uri
	 * @return
	 */
	public String getScriptContent(String uri){
		int contextIndex = uri.indexOf("/", 1);
		String _uri = uri.substring(contextIndex);
		ScriptFileHandler sfh = scriptFileHandlerMap.get(_uri);
		if(null != sfh){
			if(reload){
				try {
					sfh.readFile();
				} catch (IOException e) {
					log.error(e.toString());
				}
			}
			return sfh.getContent();
		}else{
			throw new RuntimeException("没有对应[" + uri + "]的脚本处处理适配器。");
		}
	}
	
	/**
	 * 获取脚本处理映射
	 * @return
	 */
	public Map<String, ScriptFileHandler> getScriptFileHandlerMap() {
		return scriptFileHandlerMap;
	}
	
	/**
	 * 设置脚本处理器映射
	 * @param scriptFileHandlerMap
	 */
	public void setScriptFileHandlerMap(
			Map<String, ScriptFileHandler> scriptFileHandlerMap) {
		this.scriptFileHandlerMap = scriptFileHandlerMap;
	}
	
	/**
	 * 返回文件映射
	 * @return
	 */
	public Map<String, String> getFilesMap() {
		return filesMap;
	}
	
	/**
	 * 设置文件映射
	 * @param filesMap
	 */
	public void setFilesMap(Map<String, String> filesMap) {
		this.filesMap = filesMap;
	}

	/**
	 * 返回当前实例重载属性
	 * @return
	 */
	public boolean isReload() {
		return reload;
	}

	/**
	 * 设置重载开关
	 * @param reload
	 */
	public void setReload(boolean reload) {
		this.reload = reload;
	}
}
